package com.lenovo.manufacture.Fragment;


import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;

import com.google.gson.Gson;
import com.lenovo.manufacture.R;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.http.Body;
import retrofit2.http.POST;

/**
 * A simple {@link Fragment} subclass.
 */
public class LightFragment extends Fragment {

    @BindView(R.id.img_deng)
    ImageView imgDeng;
    @BindView(R.id.kaiqi)
    Button kaiqi;
    @BindView(R.id.guanbi)
    Button guanbi;

    private View view;

    private Integer[] img = new Integer[]{R.drawable.guangdeng,R.drawable.kaideng};

    public LightFragment() {
        // Required empty public constructor
    }

    private interface BlogServer{
        @POST("search")
        Call<ResponseBody> getBlog(@Body RequestBody str);

    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_light, container, false);
        ButterKnife.bind(this,view);
        return view;
    }

    @OnClick({R.id.kaiqi, R.id.guanbi})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.kaiqi:
                initData(1);
                break;
            case R.id.guanbi:
                initData(0);
                break;
        }
    }
    private void initData(int i){
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://hh1.me:5001/Interface/UserFactoryEnvironmentalLog/")
                .build();
        BlogServer blogServer = retrofit.create(BlogServer.class);
        Map<String,Integer> map = new HashMap<>();
        map.put("isLighting",i);
        String s = new Gson().toJson(map);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json:charset=utf-8"),s);
        Call<ResponseBody> blog = blogServer.getBlog(requestBody);
        blog.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                imgDeng.setImageResource(img[i]);
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
            }
        });
    }
}
